import 'package:http/http.dart' as http;
import 'dart:convert';

import 'package:state_management_flutter_bloc/models/api_models.dart';

class PlayerApiProvider{
  String baseUrl = "https://www.easports.com/fifa/ultimate-team/api/fut/item?";
  int successCode = 200;

  ///获取远动员列表
  Future<ApiResult> fetchPlayersByCountry (String countryId,{page=1}) async {
    final response= await http.get("${baseUrl}country=$countryId&page=$page");
    return parseResponse(response);
  }

  ApiResult parseResponse(http.Response response) {
     final responseString =  jsonDecode(response.body);
    if(response.statusCode == successCode ){
      ApiResult result= ApiResult.fromJson(responseString);
      return result;
    }else{
      throw Exception('failed to load palyers');
    }
  }

  Future<ApiResult> fetchPlayersByName (String name,{page=1}) async {
    final response= await http.get("${baseUrl}name=$name&page=$page");
    return parseResponse(response);
  }

  Future<ApiResult> fetchPlayersAdvanceSearch (String nations,String leagues,String positions,{page=1}) async {
    String queryParamter = "";
    if(nations != null){
      queryParamter = "&country="+nations;
    }
    if(leagues != null){
      queryParamter += "&club="+leagues;
    }
    if(positions != null){
      queryParamter += "&position="+positions;
    }

    final response= await http.get("${baseUrl}$queryParamter");
    return parseResponse(response);
  }

}